package com.googlecode.bip.xml.importe;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import com.googlecode.bip.dao.mysql.MySQLDAOFactory;
import cx.ath.choisnet.sql.ConnectionQuery;

/**
 *
 * @author Claude
 */
public class SQLStatementCollection implements Serializable
{
    private static final long serialVersionUID = 1L;
    private final static transient Logger logger = Logger.getLogger( SQLStatementCollection.class );
    private List<String> sqlList = new ArrayList<String>();

    public synchronized void addSQLStatement( String sqlUpdate )
    {
        sqlList.add( sqlUpdate );
    }

    public synchronized void performCommits() throws NamingException, SQLException
    {
        Connection connection = getConnection();
        connection.setAutoCommit( false );

        if( logger.isDebugEnabled() ) {
            logger .debug( "performCommits()" );
            }

        try {
            ConnectionQuery connectionQuery = new ConnectionQuery( connection ) ;

            for( String s : sqlList ) {
                if( logger.isDebugEnabled() ) {
                    logger .debug( "SQL: " + s );
                    }
                connectionQuery.doUpdate( s );
                }
            }
        finally {
            connection.setAutoCommit( true );
            connection.close();
            }
    }

    private Connection getConnection()
        throws NamingException, SQLException
    {
        return MySQLDAOFactory.getConnection();
    }

}
